package com.dzf.config;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;

@Configuration//把自己放入ioc，相当于<beans>
@EnableWebSecurity
public class QqAuth2ServiceConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    AuthenticationManager authenticationManagerBean;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override //让oauth2不需要登录就能得到token
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
        System.out.println("checkTokenAccess(\"permitAll()\")");
        oauthServer.tokenKeyAccess("permitAll()") // /oauth/token
                .checkTokenAccess("permitAll()") // /oauth/check_token
                .allowFormAuthenticationForClients();
                //通过表单认证
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        System.out.println("configure()");
        System.out.println("configure(ClientDetailsServiceConfigurer clients)");
        clients.inMemory()
                .withClient("youdao").secret(passwordEncoder.encode("223344"))
                .authorizedGrantTypes("password", "authorization_code",
                        "client_credentials", "implicit", "refresh_token")
                .scopes("all")
                .autoApprove(true)
                .redirectUris("http://www.baidu.com")    // 认证成功重定向URL
                .and()
                .withClient("sobook").secret(passwordEncoder.encode("223344"))
                .authorizedGrantTypes("password", "authorization_code",
                        "client_credentials", "implicit", "refresh_token")
                .scopes("all")//访问范围 （角色信息）
                .autoApprove(true)//自动授权
                .redirectUris("http://www.baidu.com");
    }
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        System.out.println("configure(AuthorizationServerEndpointsConfigurer endpoints)");
        endpoints.authenticationManager(authenticationManagerBean)
                .userDetailsService(userDetailsService);
    }
}
